package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.em.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.controller.UserFreezeService;
import com.tanhua.server.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentsService {
    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MqMessageService mqMessageService;

    //添加评论动态 动态id 和 评论内容
    public void saveComments(String movementId, String comment) {
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0205","movement", movementId);
        //获得用户id
        Long userId = UserHolder.getUserId();

        //创建
        Comment comment1=new Comment();
        comment1.setUserId(userId);
        comment1.setContent(comment);
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCreated(System.currentTimeMillis());
        comment1.setCommentType(CommentType.COMMENT.getType());
        //先不添加动态用户的id
           Integer commentcount= commentApi.save(comment1);
    }
//前端需要评论和用户信息封装一起
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //根据动态id查询评论列表(CommentsType为二)
        List<Comment> commentList=commentApi.findComments(page,pagesize,movementId,CommentType.COMMENT);
        //判断评论是否为空
        if(CollUtil.isEmpty(commentList)){
               return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        //根据id获得所有用户且用map集合 id一一对应
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null, null);
        List<CommentVo> list =new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = userInfoMap.get(comment.getUserId());
            if(userInfo!=null){
                CommentVo commentVo = CommentVo.init(userInfo, comment);
                list.add(commentVo);
            }
        }
        return new PageResult(page,pagesize,0,list);
        //4、构造vo对象



        //5、构造返回值
    }
    //取消点赞
    public Integer unlikeComments(String movementId) {
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0206","movement",movementId);
        //查询comments表判断是否点赞
        boolean comments=commentApi.haslike(movementId,UserHolder.getUserId(),CommentType.LIKE);
        if(!comments){
            throw new BusinessException(ErrorResult.disLikeError());//用户没有点赞
        }
        //3、调用API，删除数据，返回点赞数量
         Comment comment =new Comment();
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setPublishId(new ObjectId(movementId));
        Integer counts=commentApi.delete(comment);
        //4、拼接redis的key，删除点赞状态的redis;
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return counts;//返回总的点赞数
    }
   //喜欢
    public Integer loveComments(String movementId) {
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0204","movement",movementId);

        //查询comments表判断是否点赞
        boolean comments=commentApi.haslike(movementId,UserHolder.getUserId(),CommentType.LOVE);
        //如果存在就不能点赞了
        if(comments){
            throw new BusinessException(ErrorResult.loveError());//用户已喜欢
        }
        Comment comment=new Comment();
        comment.setCommentType(CommentType.LOVE.getType());//喜欢
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(UserHolder.getUserId());//用户id
        comment.setPublishId(new ObjectId(movementId));//动态id
        Integer save = commentApi.save(comment);//返回的是所有的点赞数
        //4、拼接redis的key，将用户的喜欢状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return save;
    }
    //取消喜欢
    public Integer unloveComments(String movementId) {
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0207","movement",movementId);
        //查询comments表判断是否喜欢
        boolean comments=commentApi.haslike(movementId,UserHolder.getUserId(),CommentType.LOVE);
        if(!comments){
            throw new BusinessException(ErrorResult.disloveError());//用户没有喜欢
        }
        //3、调用API，删除数据，返回喜欢数量
        Comment comment =new Comment();
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setPublishId(new ObjectId(movementId));
        Integer counts=commentApi.delete(comment);
        //4、拼接redis的key，删除点赞状态的redis;
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return counts;//返回总的点赞数
    }
    //点赞
    public Integer likeComments(String movementId) {
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0203","movement",movementId);
        //查询comments表判断是否点赞
        boolean comments=commentApi.haslike(movementId,UserHolder.getUserId(),CommentType.LIKE);
        //如果存在就不能点赞了
        if(comments){
            throw new BusinessException(ErrorResult.likeError());//用户已点赞
        }
        Comment comment=new Comment();
        comment.setCommentType(CommentType.LIKE.getType());//喜欢
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(UserHolder.getUserId());//用户id
        comment.setPublishId(new ObjectId(movementId));//动态id
        Integer save = commentApi.save(comment);//返回的是所有的点赞数
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return save;
    }

     //评论点赞userId为唯一的评论表id
    public Integer commentsLike(String userId) {

        String key = Constants.MOVEMENTS_INTERACT_KEY + userId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        Boolean hasKey = redisTemplate.opsForHash().hasKey(key, hashKey);
        if(hasKey){
            throw new BusinessException(ErrorResult.likeError());
        }
        log.info("评论id:{}",userId);
        //添加评论点赞数
        Integer count= commentApi.saveCommentLikeCount(userId);

        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    public Integer commentsDisLike(String userId) {

        String key = Constants.MOVEMENTS_INTERACT_KEY + userId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        Boolean hasKey = redisTemplate.opsForHash().hasKey(key, hashKey);
        if(!hasKey){
            throw new BusinessException(ErrorResult.disLikeError());//用户未点赞
        }
        Integer count= commentApi.deleteCommentLikeCount(userId);
        redisTemplate.opsForHash().delete(key,hashKey);//取消后删除redis.
        return count;

    }
}
